package com.sq.partner.manager.service.impl;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.sq.partner.manager.dao.ICoreDeptDao;
import com.sq.partner.manager.dao.IGatewayAgentInfoMtDao;
import com.sq.partner.manager.dao.IGatewayAgentInfoRelaDao;
import com.sq.partner.manager.dao.IGatewayChannelInfoConfigDao;
import com.sq.partner.manager.dao.IGatewayTradInsuPlanDao;
import com.sq.partner.manager.dao.ITradAgentInfoIdDao;
import com.sq.partner.manager.dao.ITradProdInstDao;
import com.sq.partner.manager.dao.impl.GatewayTradInsuPlanDaoImpl;
import com.sq.partner.manager.mybatis.model.CoreDept;
import com.sq.partner.manager.mybatis.model.GatewayChannelInfo;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.mybatis.model.TradAgentInfo;
import com.sq.partner.manager.mybatis.model.TradAgentInfoId;
import com.sq.partner.manager.mybatis.model.TradAgentInfoRela;
import com.sq.partner.manager.mybatis.model.TradInsuPlan;
import com.sq.partner.manager.mybatis.model.TradProdInst;
import com.sq.partner.manager.service.IGatewayChannelInfoConfigService;
import com.sq.partner.manager.service.IGatewayClearCacheManager;
import com.sq.partner.manager.service.IGatewayInsureService;
import com.sq.partner.manager.util.DomainEquals;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.StrUtil;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
@Service
public class GatewayInsureServiceImpl  implements IGatewayInsureService {
	
	private static Logger logger = LogUtil.getLog(GatewayInsureServiceImpl.class);

	@Resource
	IGatewayTradInsuPlanDao gatewayTradInsuPlanDao;
	@Resource
	IGatewayAgentInfoMtDao agentInfoMtDao;
	@Resource
	ITradProdInstDao prodDao;
	
	@Resource
	ICoreDeptDao deptDao;
	
	@Resource
	IGatewayClearCacheManager gatewayClearCacheManager;
	@Resource
	IGatewayChannelInfoConfigDao gatewayChannelInfoConfigDao;
	@Resource
	IGatewayChannelInfoConfigService gatewayChannelInfoConfigService;
	@Resource
	IGatewayAgentInfoRelaDao gatewayAgentInfoRelaDao;
	@Resource
	ITradAgentInfoIdDao tradAgentInfoIdDao;
	
	@Override
	public Page<TradInsuPlan> queryTradInsuPlanPage(Page<TradInsuPlan> page) throws SQLException {
		return gatewayTradInsuPlanDao.queryTradInsuPlanPage(page);
	}

	@Override
	public Page<TradProdInst> queryPageForTradProdInst(Page<TradProdInst> page) throws SQLException {
		return prodDao.queryProdPageForInsure(page);
	}

	@Override
	public Page<CoreDept> queryPageForCoreDept(Page<CoreDept> page,String partnerNo)
			throws Exception {
		return deptDao.queryCoreDeptPage(page,partnerNo);
	}

	@Override
	public List<TradInsuPlan> queryNewBSNS(Map<String, String> map)
			throws Exception {
		return gatewayTradInsuPlanDao.queryNewBSNS(map);
	}

	@Override
	public boolean addTradInsuPlan(TradInsuPlan insuplan) throws Exception {
		boolean boo= gatewayTradInsuPlanDao.addTradInsuPlan(insuplan);
		
 		//清除缓存
		gatewayChannelInfoConfigService.clearAllCacheByChannelCode(insuplan.getPartnerNo());
		return boo;
	}

	@Override
	public boolean delTradInsuPlan(TradInsuPlan insuplan) throws Exception {
		TradInsuPlan oleInsuplan = gatewayTradInsuPlanDao.queryTradInsuPlanInfo(insuplan);
		TradProdInst prod1 = new TradProdInst();
		prod1.setTradProdCode(oleInsuplan.getTradProdCode());
		TradProdInst prod2 = prodDao.queryTradProdInst(prod1);
		//1、合作伙伴代理3、个人代理4、总对总代理
		if("3".equals(prod2.getAgentType())||"4".equals(prod2.getAgentType())){
			//根据方案号删除方案下面配置的代理信息
			gatewayAgentInfoRelaDao.delTradAgentInfoRelaByPlanNo(insuplan.getInsuPlanNo());
		}
		boolean boo=gatewayTradInsuPlanDao.delTradInsuPlan(insuplan);
		//清除缓存
		gatewayChannelInfoConfigService.clearAllCacheByChannelCode(insuplan.getPartnerNo());
		
		return boo;
	}

	@Override
	public TradInsuPlan queryTradInsuPlanInfo(TradInsuPlan insuplan)
			throws Exception {
		return gatewayTradInsuPlanDao.queryTradInsuPlanInfo(insuplan);
	}

	@Override
	public Map<String,Object> queryMapTradInsuPlanInfo(TradInsuPlan insuplan) throws Exception {
		
		return gatewayTradInsuPlanDao.queryMapTradInsuPlanInfo(insuplan);
	}
	
	@Override
	public boolean updateTradInsuPlanInfo(TradInsuPlan insuplan)throws Exception {
		TradInsuPlan oleInsuplan = gatewayTradInsuPlanDao.queryTradInsuPlanInfo(insuplan);
		boolean boo = false;
		if(!DomainEquals.domainEquals(oleInsuplan, insuplan)){//如果不想等
			boo=gatewayTradInsuPlanDao.updateTradInsuPlanInfo(insuplan);
			//清除缓存
			gatewayChannelInfoConfigService.clearAllCacheByChannelCode(insuplan.getPartnerNo());
		}else{
			boo = true;
		}
		return boo;
	}

	@Override
	public TradInsuPlan getMaxInsuPlanNo(TradInsuPlan insuplan)
			throws Exception {
		return gatewayTradInsuPlanDao.getMaxInsuPlanNo(insuplan);
	}

	@Override
	public Page<GatewayChannelInfo> queryPageForGatewayChannelInfo(
			Page<GatewayChannelInfo> page) throws Exception {
		// TODO Auto-generated method stub
		return gatewayChannelInfoConfigDao.getListByDept(page);
	}

	@Override
	public Page queryPageForTradAgentInfo(Page<TradAgentInfo> page,Map<String,Object> map)
			throws Exception {
		TradAgentInfo tradAgentInfo= page.getType();
		if("3".equals(tradAgentInfo.getAgentType())){//个人代理
			return gatewayTradInsuPlanDao.queryPageForTradAgentInfo(page,map);
		}else if("4".equals(tradAgentInfo.getAgentType())){//总对总代理
			return gatewayTradInsuPlanDao.queryPageForTradAgentInfoType4(page,map);
		}
		return null;
	}

	@Override
	public Page queryPageForTradAgentInfoEdit(Page page,
			Map<String,Object> map) throws Exception {
		String insuPlanNo = map.get("insuPlanNo")+"";
		String agentType = map.get("agentType")+"";
		page.setMap(map);
		if("3".equals(agentType)){
			return gatewayTradInsuPlanDao.queryPageForTradAgentInfoEdit(page,insuPlanNo);
		}else if("4".equals(agentType)){
			return gatewayTradInsuPlanDao.queryPageForTradAgentInfoEditType4(page,insuPlanNo);
		}
		return null;
	}

	@Override
	public List<Map> queryTradAgentInfoByInsuPlanNo(String insuPlanNo)
			throws Exception {
		return gatewayAgentInfoRelaDao.queryAgentInfoByInsuPlanNo(insuPlanNo);
	}

	@Override
	public boolean addProxyInfo(String insuPlanNo, GatewayUser gatewayuser,
			String agentTypeList) throws Exception {
		boolean flag = false;
		//1、合作伙伴代理3、个人代理4、总对总代理
		if(!StrUtil.isEmpty(agentTypeList)){
			//创建一个JsonParser
			JsonParser parser = new JsonParser();
			//通过JsonParser对象可以把json格式的字符串解析成一个JsonElement对象
			JsonElement el = parser.parse(agentTypeList);
			//把JsonElement对象转换成JsonArray
			JsonArray jsonArray = null;
			if(el.isJsonArray()){
				jsonArray = el.getAsJsonArray();
			}
			for (JsonElement jsonElement : jsonArray) {
				String id =jsonElement.getAsJsonObject().get("id").getAsString();
				String value=jsonElement.getAsJsonObject().get("value").getAsString();
				if(!StrUtil.isEmpty(id)){
					TradAgentInfoRela tradAgentInfoRela =new TradAgentInfoRela();
					tradAgentInfoRela.setAgentInfoId(Long.valueOf(id));
					tradAgentInfoRela.setInsuPlanNo(insuPlanNo);
					if(!StrUtil.isEmpty(value)){
						BigDecimal bigDecimal =new BigDecimal(value);
						bigDecimal=bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP); 
						tradAgentInfoRela.setCommRate(bigDecimal);
					}
					tradAgentInfoRela.setOperTime(new Date());
					tradAgentInfoRela.setOperUser(gatewayuser.getUserid());
					flag = gatewayAgentInfoRelaDao.addAgentInfoRela(tradAgentInfoRela);
				}
			}
		}
		
		return flag;
	}

	@Override
	public boolean updateProxyInfo(String insuPlanNo, GatewayUser gatewayuser,
			String agentTypeList) throws Exception {
		boolean flag = false;
		//1、合作伙伴代理3、个人代理4、总对总代理
		if(!StrUtil.isEmpty(agentTypeList)){
			//创建一个JsonParser
			JsonParser parser = new JsonParser();
			//通过JsonParser对象可以把json格式的字符串解析成一个JsonElement对象
			JsonElement el = parser.parse(agentTypeList);
			//把JsonElement对象转换成JsonArray
			JsonArray jsonArray = null;
			if(el.isJsonArray()){
				jsonArray = el.getAsJsonArray();
			}
			String ids="";
			for (JsonElement jsonElement : jsonArray) {
				String id =jsonElement.getAsJsonObject().get("id").getAsString();
				ids= ids+id+",";
			}
			if(ids.length()>0){
				ids=ids.substring(0, ids.length()-1);
			}
			long starttime=System.currentTimeMillis();
			synchronized(tradAgentInfoIdDao){//为保证表t_trad_agent_info_id的数据一次会话数据一致性，需要加锁
				List<String> listids2=Arrays.asList(ids.split(","));
				List<TradAgentInfoId>listids=new ArrayList();
				for(int i=0;i<listids2.size();i++){
					TradAgentInfoId tt=new TradAgentInfoId();
					tt.setAgentInfoId(Long.parseLong(listids2.get(i)));
					listids.add(tt);
				}
				tradAgentInfoIdDao.DeleteTradAgentInfoId();// 存入id前先清空表
				tradAgentInfoIdDao.SaveTradAgentInfoId(listids);
				flag=gatewayAgentInfoRelaDao.delTradAgentInfoRelaByInsuplannoAndAgentIds(insuPlanNo, ids);
			}
			logger.info("执行带IN语句耗时： "+(System.currentTimeMillis()-starttime));
			long ss=System.currentTimeMillis();
			TradAgentInfoRela tradAgentInfoRelaPlan=new TradAgentInfoRela();
			tradAgentInfoRelaPlan.setInsuPlanNo(insuPlanNo);
			 List<TradAgentInfoRela> gatewayAgentInfoRelaAll =  gatewayAgentInfoRelaDao.queryTradAgentInfoRelaByMap(tradAgentInfoRelaPlan);
			 logger.info("根据方案号"+insuPlanNo+"查询代理信息关系表t_trad_agent_info_rela耗时： "+(System.currentTimeMillis()-ss));
//			 TradAgentInfoRela oldAgentInfoRela
			for (JsonElement jsonElement : jsonArray) {
				String id =jsonElement.getAsJsonObject().get("id").getAsString();
				String value=jsonElement.getAsJsonObject().get("value").getAsString();
				JsonElement busEl=jsonElement.getAsJsonObject().get("businessRate");
				String businessRate="";
				if(busEl!=null){
					businessRate=busEl.getAsString();
				}
				
				String marketRate="";
				JsonElement marEl=jsonElement.getAsJsonObject().get("marketRate");
				if(marEl!=null){
					marketRate=marEl.getAsString();
				}
				boolean equ=false;
				for(int i=0;i<gatewayAgentInfoRelaAll.size();i++){
					TradAgentInfoRela map=gatewayAgentInfoRelaAll.get(i);
					 String id2=map.getAgentInfoId()==null?"":(map.getAgentInfoId()+"");
					 String comm_rate=map.getCommRate()==null?"":(map.getCommRate()+"");
					 String business_Rate=map.getBusiness()==null?"":(map.getBusiness()+"");
					 String market_Rate=map.getMarket()==null?"":(map.getMarket()+"");
					 if(id.equals(id2)&&value.equals(comm_rate)&&business_Rate.equals(businessRate)&&market_Rate.equals(marketRate)){//如果AGENT_INFO_ID和comm_rate没有变化，不需要去操作数据库
						 gatewayAgentInfoRelaAll.remove(i);
						 equ=true;
						 flag=equ;
						 break;
					 }
					 
				}
				
				 if(!equ&&!StrUtil.isEmpty(id)){
						TradAgentInfoRela tradAgentInfoRela =new TradAgentInfoRela();
						tradAgentInfoRela.setAgentInfoId(Long.valueOf(id));
						tradAgentInfoRela.setInsuPlanNo(insuPlanNo);
						if(!StrUtil.isEmpty(value)){
							BigDecimal bigDecimal =new BigDecimal(value);
							bigDecimal=bigDecimal.setScale(6, BigDecimal.ROUND_HALF_UP); 
							tradAgentInfoRela.setCommRate(bigDecimal);
						}
						if(!StrUtil.isEmpty(marketRate)){
							BigDecimal bigDecimal =new BigDecimal(marketRate);
							bigDecimal=bigDecimal.setScale(6, BigDecimal.ROUND_HALF_UP); 
							tradAgentInfoRela.setMarket(bigDecimal);
						}
						if(!StrUtil.isEmpty(businessRate)){
							BigDecimal bigDecimal =new BigDecimal(businessRate);
							bigDecimal=bigDecimal.setScale(6, BigDecimal.ROUND_HALF_UP); 
							tradAgentInfoRela.setBusiness(bigDecimal);
						}
						tradAgentInfoRela.setOperTime(new Date());
						tradAgentInfoRela.setOperUser(gatewayuser.getUserid());
						long bb=System.currentTimeMillis();
						flag = gatewayAgentInfoRelaDao.addOrUpdateTradAgentInfoRela(tradAgentInfoRela);
						logger.info("测试每个更新 耗时："+(System.currentTimeMillis()-bb));
				}
		  }
			
		}
		return flag;
	}

	@Override
	public boolean copyAddTradInsuPlan(TradInsuPlan insuplan,String oldPlanNo, boolean isCopy)throws Exception {
		boolean boo= gatewayTradInsuPlanDao.addTradInsuPlan(insuplan);
		if(isCopy){
			gatewayAgentInfoRelaDao.copyTradAgentInfoRela(insuplan.getInsuPlanNo(), oldPlanNo);
		}
 		//清除缓存
		gatewayChannelInfoConfigService.clearAllCacheByChannelCode(insuplan.getPartnerNo());
		return boo;
	}

	@Override
	public boolean proxyInfoIsEmpty(String insuPlanNo)throws Exception {
		boolean flag=false;
		List<Map> list = gatewayAgentInfoRelaDao.queryAgentInfoByInsuPlanNo(insuPlanNo);
		if(list==null||list.isEmpty()){
			flag = true;
		}
		return flag;
	}

	@Override
	public boolean updateTradInsuPlanApplicationNo(TradInsuPlan insuplan)
			throws Exception {
		boolean returnFlag = gatewayTradInsuPlanDao.updateTradInsuPlanApplicationNo(insuplan);
		if(returnFlag){
			//清除缓存
			gatewayChannelInfoConfigService.clearAllCacheByChannelCode(insuplan.getPartnerNo());
		}
		return returnFlag;
	}

	@Override
	public Page<CoreDept> queryPageDept(Page<CoreDept> page,String deptCode) throws Exception {
		// TODO Auto-generated method stub
		return  deptDao.queryPageDept(page, deptCode);
	}


	@Override
	public boolean deleteCommPlanRate(Map<String, Object> map) throws Exception {
		return agentInfoMtDao.deleteCommPlanRate(map);
	}

	@Override
	public boolean addTradAgentInfoRelaBach(
			Map<String, Object> map,List<TradAgentInfoRela> tradAgentInfoRelas) throws Exception {
		/**删除原关联的方案*/
		agentInfoMtDao.deleteCommPlanRate1(map);
		return gatewayAgentInfoRelaDao.addTradAgentInfoRelaBach(tradAgentInfoRelas);
	}

	@Override
	public boolean deleteCommPlanRate1(Map<String, Object> map)
			throws Exception {
		return agentInfoMtDao.deleteCommPlanRate1(map);
	}

	@Override
	public Page<CoreDept> queryPageForCoreDeptJSCD(Page<CoreDept> page,
			String partnerNo) throws Exception {

		return deptDao.queryCoreDeptPageJSCD(page,partnerNo);
	}
}
